#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>
#include <cstdio>

void childWrite(int fd)
{
    char buf[1024];

    sprintf(buf, "I am child, my fd: %d", getpid());

    ssize_t count = write(fd, buf, strlen(buf));

    printf("child write word: %ld\n", count);
}

void parentRead(int fd)
{
    char buf[1024];

    int count = read(fd, buf, sizeof(buf) - 1);

    printf("parent get word: %d\n", count);
    printf("%s", buf);
}

void test()
{
    int pfd[2] = { 0 };
    int n = pipe(pfd);

    if (n != 0)
    {
        return;
    }

    int fd = fork();

    if (fd == 0)
    {
        close(pfd[0]);
        childWrite(pfd[1]);
        close(pfd[1]);
        exit(0);
    }
    else
    {
        sleep(1);
        close(pfd[1]);
        parentRead(pfd[0]);
        close(pfd[0]);
    }

    wait(nullptr);
}

int main()
{
    test();
    
    return 0;
}


